// This Photoshop script scales images in a folder to specified size
// Requirements:
// 1. Image is "name.BmpErasedCCs.bmp"
// 2. The corresponding location file is "name.SelMBs.xml"
// 3. Files 1 and 2 are located in the same folder
// Writes the image "name.Resized.bmp" in the work folder
// Note: Doesn't work recursively

// set units
var strtRulerUnits = app.preferences.rulerUnits;
var strtTypeUnits = app.preferences.typeUnits;
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.POINTS;

// select the source folder
var workFolder = Folder.selectDialog("Select work folder","~");

// get bitmaps
if(workFolder != null)
{
	var bmpList = new Array();
	var bmpCount = 0;
	var fileList = workFolder.getFiles();
	for( i = 0; i <fileList.length; i++)
	{
		if(fileList[i] instanceof File)
		{
			filename = fileList[i].fsName;
			temp = getSubString(filename,null,".BmpErasedCCs.bmp");
			if(temp != null)
			{
				bmpList.push(fileList[i].fsName);
				bmpCount++;
			}
		}
	}
}

var i;
var currDoc;
var saveDoc;
var currXML;
var text;
var xScale;
var yScale;
var resolution;
var noExtension;
var saveOption = new BMPSaveOptions();
saveOption.alphaChannels = false;
saveOption.depth = BMPDepthType.TWENTYFOUR;
saveOption.rleCompression = false;

// scale each image
for (i = 0; i < bmpCount; i++)
{
	currDoc = open(File(bmpList[i]));
	noExtension = getSubString(bmpList[i], null,".BmpErasedCCs.bmp");
	currXML = new File(noExtension+".SelMBs.xml");
	currXML.open ("r","TEXT");
	text = currXML.read();
	xScale = parseFloat(getSubString(text,"<ScaleX>", "</ScaleX>"));
	yScale = parseFloat(getSubString(text,"<ScaleY>", "</ScaleY>"));
	//xScale = yScale;
	resolution = 100;//resolution = parseFloat(getSubString(text,"<Resolution>", "</Resolution>"));
	//alert("xScale: "+xScale+", yScale: "+yScale+", resolution: "+resolution);
	currDoc.resizeImage(currDoc.width*xScale,currDoc.height*yScale,resolution,ResampleMethod.NEARESTNEIGHBOR);
	currXML.close();
	saveDoc = new File(noExtension+".Resized.bmp");
	currDoc.saveAs(saveDoc,saveOption);
	currDoc.close();
}

// restore units
app.preferences.rulerUnits = strtRulerUnits;
app.preferences.typeUnits = strtTypeUnits;

// get the string between startTag and endTag
function getSubString (data, startTag, endTag)
{
   if( startTag != null) {
	start = data.indexOf(startTag);
	if(start == -1) return null;
	startLen = start+startTag.length;
   } else {
   	startLen = 0;	
   }
   
   if(endTag != null) {
   	end  = data.indexOf(endTag);
   	if(end == -1) return null;
   } else {
   	end = data.length;
   }
   return data.substring(startLen , end);
}